from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.filters import OrderingFilter
from goods.models import GoodsCategory, SKU
from goods.serializers import GoodsSerializers, SKUIndexSerializers, GoodsHistorySerializers
from goods.utils import GoodsPage
from drf_haystack.viewsets import HaystackViewSet
from django_redis import get_redis_connection


class CategoryView(APIView):

    def get(self, request, pk):
        # 查询分类信息
        cat3 = GoodsCategory.objects.get(pk=pk)
        # 根据第三极分类查询一二级分类
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name
        })


class GoodsView(ListAPIView):

    serializer_class = GoodsSerializers
    # 指定分页器
    pagination_class = GoodsPage
    # 指定过滤
    filter_backends = [OrderingFilter]
    ordering_fields = ['price', 'sales', 'create_time']

    def get_queryset(self):
        pk = self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)


class SKUindexView(HaystackViewSet):

    index_models = [SKU]  # 指定检索的对象模型类
    serializer_class = SKUIndexSerializers
    pagination_class = GoodsPage


class GoodsHistoryView(CreateAPIView, ListAPIView):
    '''post方法处理浏览记录保存，get方法处理浏览历史显示'''

    # queryset = SKU.objects.filter(id__in=)
    # serializer_class = GoodsHistorySerializers

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return GoodsHistorySerializers
        else:
            return GoodsSerializers

    def get_queryset(self):
        # 根据当前用户从redis中获取商品id
        conn = get_redis_connection('history')
        # 根据商品id查询商品对象
        sku_ids = conn.lrange('history_%s' % self.request.user.id, 0, 10)

        return SKU.objects.filter(id__in=sku_ids)